//
//  CircleViewController.m
//  安好
//
//  Created by lianchuang on 14-11-3.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "CircleViewController.h"
#import "AssociatedWithIViewController.h"
#import "AHNetWork.h"
#import "SquareModelData.h"
#import "iflyMSC/IFlyRecognizerView.h"
#import "iflyMSC/IFlyRecognizerViewDelegate.h"
#define APPID @"5313e44f"


@interface CircleViewController ()<IFlyRecognizerViewDelegate
>
{
    UIView *hiddenView;
    UITapGestureRecognizer *tapna;
    
}


@end

@implementation CircleViewController

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[AFHTTPRequestOperationManager manager].operationQueue cancelAllOperations];
    [self hiddenActionView];
    

    if (self.pop1) {
        [self.pop1 dismiss];

    }
    if (self.pop2) {
        [self.pop2 dismiss];
        
    }
    if (self.pop) {
        [self.pop dismiss];

    }
    [self.navigationController.navigationBar removeGestureRecognizer:tapna];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreNoticeNotification object:nil];
    static int squareInt = 1;
    if (squareInt==1) {
        squareInt++;
    }else{
    
    
    if ([[self.segmentedControl titleForSegmentAtIndex:1] isEqualToString:@"我的圈子"]) {
        UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
        [rightButton setImage:[UIImage imageNamed:@"公用_更多"] forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(rightButtonAddMoreClicked:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        self.navigationItem.rightBarButtonItem = rightBarButtonItem;
        [self redDot];
    }
    

    [self segmentedControlClick:self.segmentedControl];
    }
    
    tapna = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toTop)];
    [self.navigationController.navigationBar addGestureRecognizer:tapna];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.squarePage =1;
    self.type= 6;
    self.edgesForExtendedLayout=UIRectEdgeNone;

    if (!self.threadListBaseClass) {
        self.threadListBaseClass=[[ThreadListBaseClass alloc]init];
    }
    if(!self.popViewArray){
        self.popViewArray=[[NSMutableArray alloc]init];

    }
    if(!self.secondCircleArray){
        self.secondCircleArray=[[NSMutableArray alloc]init];
        
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerViewNot:) name:kDidGetAndStoreNoticeNotification object:nil];

    
    self.pidAndGid = [[NSMutableDictionary alloc]initWithCapacity:10];
    [self.pidAndGid setObject:@"0" forKey:@"pid"];
    [self.pidAndGid setObject:@"0" forKey:@"gid"];

    
    
    
    
    
    
    
//    self.squareArray= [[NSMutableArray alloc]initWithCapacity:10];
    self.circleArray= [[NSMutableArray alloc]initWithCapacity:10];

    
    // Do any additional setup after loading the view from its nib.
//    [self.navigationController.navigationBar setBarTintColor:[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16]];
//
//    //nav半透明设置
//    self.navigationController.navigationBar.translucent=NO;
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"广场",@"圈子",nil];
    
    //初始化UISegmentedControl
    self.segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    [self.segmentedControl addTarget:self action:@selector(segmentedControlClick:) forControlEvents:UIControlEventValueChanged];
    //MyNSLog("%f",self.view.frame.size.width);
    self.segmentedControl.frame = CGRectMake(0.0, 10.0, 150.0, 24.0);
    self.segmentedControl.selectedSegmentIndex = 0;//设置默认选择项索引
    self.segmentedControl.layer.masksToBounds = YES;
    self.segmentedControl.layer.cornerRadius = 4.0;
    self.segmentedControl.layer.borderWidth = 1.0;
    self.segmentedControl.backgroundColor=[ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    self.segmentedControl.layer.borderColor =[[UIColor colorWithRed:1 green:1 blue:1 alpha:0.9] CGColor];
    self. segmentedControl.tintColor =[UIColor colorWithRed:1 green:1 blue:1 alpha:0.9];
    self.navigationItem.titleView = self.segmentedControl;

    
    
    

    
    
    
    [self squareleftAndRightButton];
    
    
    
    
    
    
    
    [self initWithScrollView];
    NSString * userIsLogin =  [NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]];
    //是否为登录状态
    if ([userIsLogin length]==0  || [[UserManager shareInstance]getUserIsLogin ] == nil) {
        self.segmentedControl.selectedSegmentIndex=0;
    }else{
        self.segmentedControl.selectedSegmentIndex=1;
        
    }
    [self segmentedControlClick:self.segmentedControl];
    

    


    
}
-(void)toTop{
    if (!self.squareView.hidden&&self.threadListBaseClass.data.count>0) {
//        [self.squareView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
//                               atScrollPosition:UITableViewScrollPositionTop
//                                       animated:YES];
        //CGRectMake(0, 0, 1, 1)可以直接返回到UITableView的最顶端
        [self.squareView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    }


}
-(void)squareleftAndRightButton{
    
    
    UIButton *leftButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [leftButton setImage:[UIImage imageNamed:@"公用_筛选@2x.png"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [rightButton setImage:[UIImage imageNamed:@"公用_更多"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    [self redDot];
}
-(void)squareRightButton{
    self.navigationItem.leftBarButtonItem = nil;
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [rightButton setImage:[UIImage imageNamed:@"公用_添加"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonAddCircleClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}
-(void)initWithScrollView{

    

    
    self.squareView = [[UITableView alloc]initWithFrame:CGRectMake(0.0, 0.0, kScreenWidth,kScreenHeight-self.tabBarController.tabBar.frame.size.height-64) style:UITableViewStylePlain];
    self.squareView.delegate = self;
    self.squareView.dataSource = self;
    [self.squareView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉系统的分割线
    [self.view addSubview:self.squareView];
    [self.squareView addFooterWithTarget:self action:@selector(loadSquareData)];
    
    [self.squareView addHeaderWithTarget:self action:@selector(uploadSquareData)];
    
    
    
    
    self.circleView = [[UITableView alloc]initWithFrame:CGRectMake(0.0, 0.0, kScreenWidth,kScreenHeight-self.tabBarController.tabBar.frame.size.height-64) style:UITableViewStylePlain];
    self.circleView.delegate = self;
    self.circleView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.circleView.showsHorizontalScrollIndicator = NO;
    self.circleView.showsVerticalScrollIndicator = NO;
    //隐藏系统的cell之间的分割线
    [self.circleView setSeparatorStyle:UITableViewCellSeparatorStyleNone];    [self.view addSubview:self.circleView];
    
    
//    [self headerView];
    
    
    self.squareView.hidden = YES;
    self.circleView.hidden = YES;


    
   
}
-(void)headerViewNot:(NSNotification *)not{
    for (UIView *view in self.squareView.tableHeaderView.subviews) {
        [view removeFromSuperview];
    }
    self.fkSearchBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    self.fkSearchBar.fkSearchRequestDelegate = self;
    //    searchBar.tintColor = [BACK_BACKGROUNDCOLOR_16
//    [self.squareView setTableHeaderView:self.fkSearchBar];
    
    
    if ([[[SystemMessageCenter instance]selectAllNoReadedSecretaryNoticeMessage] count]>0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth/2-80, self.fkSearchBar.frame.size.height+15, 160, 30)];
        view.backgroundColor = [UIColor clearColor];

        
        UIImageView *imageHead = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, view.frame.size.height, view.frame.size.height)];
        imageHead.layer.masksToBounds = YES;
        imageHead.layer.cornerRadius = 3.0;
        imageHead.layer.borderWidth = 0.0;
        imageHead.backgroundColor = [UIColor clearColor];
      NoticeData *noticData =  [[SystemMessageCenter instance]getTheNewestSecretaryNoticeMessage];
        
        [imageHead setImageURLStr:noticData.avatar placeholder:[UIImage imageNamed:@"默认头像"]];
        
        [view addSubview:imageHead];
        
        
        NSString *text = [NSString stringWithFormat:@"你有%lu条新信息",(unsigned long)[[[SystemMessageCenter instance] selectAllNoReadedSecretaryNoticeMessage] count]];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(imageHead.frame.size.width+3, 0, view.frame.size.width-(imageHead.frame.size.width+3), view.frame.size.height) text:text font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13] textColor:TITLE_ARTICLE_CONTENTFONT_COLOR backgroundColor:[UIColor clearColor] numberOfLines:1 lineSpacing:0];
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.masksToBounds = YES;
        label.layer.cornerRadius = 3.0;
        label.layer.borderWidth = 0.0;
        label.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
        label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width+10, view.frame.size.height);
        [view addSubview:label];
        
        view.frame = CGRectMake((kScreenWidth-(imageHead.frame.size.width+3+label.frame.size.width))/2, self.fkSearchBar.frame.size.height+15, imageHead.frame.size.width+3+label.frame.size.width, 30);
        
        
        UIView *backView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.fkSearchBar.frame.size.height+5*2+view.frame.size.height)];
        [backView addSubview:self.fkSearchBar];
        [backView addSubview:view];
        [self.squareView setTableHeaderView:backView];
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pushAss)];
        [view addGestureRecognizer:tap];

    }else{
        UIView *backView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.fkSearchBar.frame.size.height)];
        [backView addSubview:self.fkSearchBar];
        [self.squareView setTableHeaderView:backView];
    }
    
    

    [self redDot];

    
    

    
    
}
-(void)redDot{
    UIButton  *rightButton = (UIButton *)[self.navigationItem.rightBarButtonItem customView];
    if ([[[rightButton imageView] image] isEqual:[UIImage imageNamed:@"公用_更多"]]) {
        
        
        
        if ([[[SystemMessageCenter instance] selectAllNoReadedSecretaryNoticeMessage] count]<=0) {
            for (UIView *view in rightButton.subviews) {
                if ([view isKindOfClass:[UIImageView class]]) {
                    if ([[(UIImageView*)view  image] isEqual:[UIImage imageNamed:@"point2"]]) {
                        [view removeFromSuperview];
                    }
                }
                
            }
        }else{
            
            UIImageView *redDot = [[UIImageView alloc]initWithFrame:CGRectMake(rightButton.frame.size.width-10, 0, 10, 12)];
            redDot.image =[UIImage imageNamed:@"point2"];
            [rightButton addSubview:redDot];
        }
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REDDOT" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REDDOT1" object:nil];

}
-(void)pushAss{
    self.logintag = 1;
    [self isLogin];
}
#pragma mark -
#pragma mark -- click
-(void)rightButtonClicked:(UIButton *)sender
{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    NSArray *titles = @[@"与我相关",@"查看全部", @"置顶贴", @"精华贴",@"最新贴",@"有图贴",@"无图贴"];
    NSArray *images = @[@"回复我的_normal",@"广场_全部", @"广场_置顶", @"广场_精华",@"广场_新帖",@"广场_有图",@"广场_无图"];
    NSArray *selectimages = @[@"回复我的_pressed",@"广场_全部", @"广场_置顶", @"广场_精华",@"广场_新帖",@"广场_有图",@"广场_无图"];

    self.pop = [[PopoverView alloc] initWithPoint:point titles:titles images:images selectImage:selectimages];
    
    __block CircleViewController *myself = self;
    self.pop.selectRowAtIndex = ^(NSInteger index){
        //MyNSLog("select index:%d", index);
        [myself.pidAndGid setObject:@"0" forKey:@"pid"];
        [myself.pidAndGid setObject:@"0" forKey:@"gid"];
        switch (index) {
            case 0:{
                myself.logintag = 1;
                [myself isLogin];

            }
                
                break;

                //	筛选类型:默认为0  1：置顶2：精华3：new 4：是否图片5：无图帖6：推荐
            case 1:
            {
                if (myself.type!=0) {
                    myself.type = 0;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];
                    

                }
            }
                break;
            case 2:
            {
                if (myself.type!=1) {
                    myself.type = 1;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];

                }
            }
                break;
            case 3:
            {
                if (myself.type!=2) {
                    myself.type = 2;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];

                }
            }
                break;
            case 4:
            {
                if (myself.type!=3) {
                    myself.type = 3;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];

                }
            }
                break;
            case 5:
            {
                if (myself.type!=4) {
                    myself.type = 4;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];

                }
            }
                break;
            case 6:
            {
                if (myself.type!=5) {
                    myself.type = 5;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];
                    
                }
            }
                break;
                
            default:
            {
                if (myself.type!=0) {
                    myself.type = 0;
                    myself.squarePage = 1;
                    //[self.threadListBaseClass.data removeAllObjects];
                    [myself loadSquareData];
                    
                }
            }
                break;
        }
    };
    [self.pop show];
}
-(void)leftButtonClicked:(UIButton *)sender
{
    
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",LOCAL_GROUP_LISTONE_key]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    
    if([fileManager fileExistsAtPath:path]){//文件是否存在
        [self.popViewArray removeAllObjects];
        NSDictionary *responseObject = [[NSDictionary alloc]initWithContentsOfFile:path];
        
        for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
            CircleModelData *circlemodelData = [CircleModelData modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
            [self.popViewArray addObject:circlemodelData];
        }
        
        [self creatPopView:sender];
    }else{
    
    [self loadCircleDataPop:sender];
    }
    

}
//创建popview
-(void)creatPopView:(UIButton *)sender{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 54);
    
    
    NSMutableArray *titles = [[NSMutableArray alloc]initWithCapacity:10];
    NSMutableArray *images = [[NSMutableArray alloc]initWithCapacity:10];

    
    
    
    for (int i=0; i<self.popViewArray.count; i++) {
        [titles addObject:[(CircleModelData *)[self.popViewArray objectAtIndex:i] title]];
        [images addObject:[(CircleModelData *)[self.popViewArray objectAtIndex:i] icon]];

    }
    

    
    
    
    NSMutableArray  *imageRights = [[NSMutableArray alloc]initWithCapacity:10];
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[(CircleModelData*)[self.popViewArray objectAtIndex:0] title]]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {//没文件的情况
        
        NSDictionary *responseObject = [[NSDictionary alloc]initWithContentsOfFile:path];
        
        [self.secondCircleArray removeAllObjects];
        /**
         添加全部
         */
        GroupUserModel *circlemd = [[GroupUserModel alloc]init];
        [self.pidAndGid setObject:@"0"forKey:@"pid"];
        [self.pidAndGid setObject:[NSString stringWithFormat:@"%@",[(CircleModelData *)[self.popViewArray objectAtIndex:0] gid]] forKey:@"gid"];

        [circlemd setGid:[self.pidAndGid objectForKey:@"gid"]];
        [circlemd setPid:[self.pidAndGid objectForKey:@"pid"]];
        [circlemd setTitle:@"全部"];
        [self.secondCircleArray addObject:circlemd];
        
        for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
            GroupUserModel *groupUserModel = [GroupUserModel modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
            [self.secondCircleArray addObject:groupUserModel];
        }
        
        NSMutableArray *tempArray = [[NSMutableArray alloc]initWithCapacity:10];
        NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]initWithCapacity:10];
        NSMutableDictionary *titletempDict = [[NSMutableDictionary alloc]initWithCapacity:10];
        
        for (int i=0; i<self.secondCircleArray.count; i++) {
            
            [tempArray addObject:[(CircleModelData*)[self.secondCircleArray objectAtIndex:i] title]];
            
            
        }
        
        [titletempDict setObject:tempArray forKey:@"title"];
        
        [tempDict addEntriesFromDictionary:self.pop1.titleAndImageRightDict];
        [tempDict setObject:titletempDict forKey:[(CircleModelData*)[self.popViewArray objectAtIndex:0] title]];
        [self.pop1 setTitleAndImageRightDict:tempDict index:0];
        for (int i=0; i<self.secondCircleArray.count; i++) {
            
            [imageRights addObject:[(CircleModelData*)[self.secondCircleArray objectAtIndex:i] title]];
            
            
        }
        
        
    }
/*
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[(CircleModelData*)[self.popViewArray objectAtIndex:0] title]]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {//没文件的情况
    
        [self.secondCircleArray addObjectsFromArray:[NSArray arrayWithContentsOfFile:0]];

        
        for (int i=0; i<self.secondCircleArray.count; i++) {
            
            [imageRights addObject:[(CircleModelData*)[self.secondCircleArray objectAtIndex:i] title]];
            
            
        }
    
    }
    */
    
    
    NSMutableArray  *imageRights1 = [[NSMutableArray alloc]initWithCapacity:10];
    
    NSMutableArray  *imageRights2 = [[NSMutableArray alloc]initWithCapacity:10];
    
    NSMutableArray  *imageRights3 = [[NSMutableArray alloc]initWithCapacity:10];
    
    NSMutableArray  *imageRights4 = [[NSMutableArray alloc]initWithCapacity:10];
    
    NSMutableDictionary *titleAndImageRightDictsub = [[NSMutableDictionary alloc]initWithCapacity:10];
    [titleAndImageRightDictsub setObject:imageRights forKey:@"title"];
    
    NSMutableDictionary *titleAndImageRightDictsub1 = [[NSMutableDictionary alloc]initWithCapacity:10];
    [titleAndImageRightDictsub1 setObject:imageRights1 forKey:@"title"];
    
    NSMutableDictionary *titleAndImageRightDictsub2 = [[NSMutableDictionary alloc]initWithCapacity:10];
    [titleAndImageRightDictsub2 setObject:imageRights2 forKey:@"title"];
    
    NSMutableDictionary *titleAndImageRightDictsub3 = [[NSMutableDictionary alloc]initWithCapacity:10];
    [titleAndImageRightDictsub3 setObject:imageRights3 forKey:@"title"];
    NSMutableDictionary *titleAndImageRightDictsub4 = [[NSMutableDictionary alloc]initWithCapacity:10];
    [titleAndImageRightDictsub4 setObject:imageRights4 forKey:@"title"];
    
    NSMutableDictionary *titleAndImageRightDict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [titleAndImageRightDict setObject:titleAndImageRightDictsub forKey:[titles objectAtIndex:0]];
    [titleAndImageRightDict setObject:titleAndImageRightDictsub1 forKey:[titles objectAtIndex:1]];
    
    [titleAndImageRightDict setObject:titleAndImageRightDictsub2 forKey:[titles objectAtIndex:2]];
    [titleAndImageRightDict setObject:titleAndImageRightDictsub3 forKey:[titles objectAtIndex:3]];
    
    [titleAndImageRightDict setObject:titleAndImageRightDictsub4 forKey:[titles objectAtIndex:4]];
    
    
    
    
    self.pop1 = [[PopoverView1 alloc] initWithPoint:point titles:titles images:images titleAndImageRightDict:titleAndImageRightDict];
    
    __block CircleViewController *safeSelf = self;
    self.pop1.selectRowAtIndex = ^(NSInteger index){
        //MyNSLog("select index:%d", index);
        safeSelf.type = 0;

        
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        // 2.2.获得文件的全路径
        NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[(CircleModelData*)[safeSelf.popViewArray objectAtIndex:index] title]]];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        if ([fileManager fileExistsAtPath:path]) {//没文件的情况

            NSDictionary *responseObject = [[NSDictionary alloc]initWithContentsOfFile:path];
            
            [safeSelf.secondCircleArray removeAllObjects];
            /**
             添加全部
             */
            GroupUserModel *circlemd = [[GroupUserModel alloc]init];
            
            [safeSelf.pidAndGid setObject:[NSString stringWithFormat:@"%@",[(CircleModelData *)[safeSelf.popViewArray objectAtIndex:index] pid]] forKey:@"pid"];
            [safeSelf.pidAndGid setObject:[NSString stringWithFormat:@"%@",[(CircleModelData *)[safeSelf.popViewArray objectAtIndex:index] gid]] forKey:@"gid"];
            [circlemd setGid:[safeSelf.pidAndGid objectForKey:@"gid"]];
            [circlemd setPid:[safeSelf.pidAndGid objectForKey:@"pid"]];
            [circlemd setTitle:@"全部"];
            [safeSelf.secondCircleArray addObject:circlemd];
            
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                GroupUserModel *groupUserModel = [GroupUserModel modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                [safeSelf.secondCircleArray addObject:groupUserModel];
            }
            
            NSMutableArray *tempArray = [[NSMutableArray alloc]initWithCapacity:10];
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]initWithCapacity:10];
            NSMutableDictionary *titletempDict = [[NSMutableDictionary alloc]initWithCapacity:10];
            
            for (int i=0; i<safeSelf.secondCircleArray.count; i++) {
                
                [tempArray addObject:[(CircleModelData*)[safeSelf.secondCircleArray objectAtIndex:i] title]];
                
                
            }
            
            [titletempDict setObject:tempArray forKey:@"title"];
            
            [tempDict addEntriesFromDictionary:safeSelf.pop1.titleAndImageRightDict];
            [tempDict setObject:titletempDict forKey:[(CircleModelData*)[safeSelf.popViewArray objectAtIndex:index] title]];
            [safeSelf.pop1 setTitleAndImageRightDict:tempDict index:index];
            
            
            
 
            
            
            
        }else{
        
        
        [safeSelf loadCircleDataPopTow:index];
        }
        
    };
    self.pop1.selectRowAtIndex(0);//默认选中第一个

    self.pop1.selectRowAtRightIndex = ^(NSInteger index){
        //MyNSLog("select Right index:%d", index);
        [safeSelf.pidAndGid setObject:[(GroupUserModel*)[safeSelf.secondCircleArray objectAtIndex:index] pid] forKey:@"pid"];
        [safeSelf.pidAndGid setObject:[(GroupUserModel*)[safeSelf.secondCircleArray objectAtIndex:index] gid] forKey:@"gid"];
        safeSelf.squarePage = 1;
        safeSelf.type = 0;
        [safeSelf.threadListBaseClass.data removeAllObjects];
        [safeSelf loadSquareData];
    
        
        
    };
    [self.pop1 show];
}

-(IBAction)rightButtonAddCircleClicked:(id)sender{
    self.logintag=0;
    [self isLogin];
}
/**
 *  圈子 变成我的圈子的时候
 *
 *  @param sender 右侧变成更多的button
 */
-(IBAction)rightButtonAddMoreClicked:(UIButton *)sender{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);

    
    NSArray *titles = @[@"与我相关",@"添加圈子", @"管理圈子"];
    NSArray *images = @[@"回复我的_normal",@"添加圈子_normal", @"管理圈子_normal"];
    NSArray *selectimages = @[@"回复我的_pressed",@"添加圈子_pressed", @"管理圈子_pressed"];
    
    
    
    self.pop2 = [[PopoverView alloc] initWithPoint:point titles:titles images:images selectImage:selectimages];
    __block CircleViewController *mySelf = self;
    self.pop2.selectRowAtIndex = ^(NSInteger index){
        //MyNSLog("select index:%d", index);
        switch (index) {
            case 0:{
                mySelf.logintag=1;
                [mySelf isLogin];

            }
                
                break;
            case 1:
            {
                [mySelf rightButtonAddCircleClicked:nil];
            }
                break;
            case 2:
            {
                CircleManagementViewController *cmVc = nil;
                if (kScreenWidth == 414) {
                    cmVc = [[CircleManagementViewController alloc]initWithNibName:@"CircleManagementViewController414" bundle:nil];
                }else{
                    cmVc = [[CircleManagementViewController alloc]initWithNibName:@"CircleManagementViewController" bundle:nil];

                }
                
                cmVc.circleArray =mySelf.circleArray;
                [mySelf.navigationController pushViewController:cmVc animated:YES];
            }
                break;
                
            default:
                break;
        }
    };
    [self.pop2 show];
}
/**
 *  segmentedControl改变时需要改变view
 *
 *  @param sender
 */
-(IBAction)segmentedControlClick:(id)sender{
    switch (self.segmentedControl.selectedSegmentIndex) {
        case 0:
        {
            [self squareleftAndRightButton];
//            if (self.squarePage<=1) {
//                [self.squareView setContentOffset:CGPointMake(0, self.fkSearchBar.frame.size.height) animated:YES];
//
//            }
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [NSThread sleepForTimeInterval:1.0];

                if (!self.threadListBaseClass.data.count>0) {
                    [self loadSquareData];

                }else{
//                    [self.squareView reloadData];
                }
            });

            static int squareInt = 1;
            if (squareInt==1) {
                squareInt++;
                if (self.squareView.hidden&&!self.circleView.hidden) {
                    [UIView animateWithDuration:0.5f animations:^{
                        
                        self.squareView.hidden = NO;
                        self.circleView.hidden = YES;
                    }];
                }
            }else{
                
                if (self.squareView.hidden&&self.circleView.hidden&&squareInt!=1) {
                    
                }else{
                    
                    
                    [UIView animateWithDuration:0.5f animations:^{
                        self.squareView.hidden = NO;
                        self.circleView.hidden = YES;
                    }];
                }
            }
            
            


        }
            break;
        case 1:
        {
            [self squareRightButton];
            
            

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [NSThread sleepForTimeInterval:1.0];
                
                [self loadTableData];

//                dispatch_async(dispatch_get_main_queue(), ^{

//                });
            });
            [UIView animateWithDuration:0.5f animations:^{
                self.squareView.hidden = YES;
                self.circleView.hidden = NO;
                
            }];
        }
            break;
            
        default:
            break;
    }
    
    
}
-(void)loadTableData{
    NSString * userIsLogin =  [NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]];
    
    if ([userIsLogin length]==0 || [[UserManager shareInstance]getUserIsLogin ] == nil) {
        [self loadCircleData];
        
    }else{
        [self loadMyAttentionCircleData];
    }
}
-(void)uploadSquareData{
    self.squarePage = 1;
    //[self.threadListBaseClass.data removeAllObjects];
    [self loadSquareData];
}
-(void)loadSquareData{
    static int squareInt = 1;
//    if (squareInt==1) {
        [self showActionView];

//    }

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];//平台 ios/android	必选
    [dict setObject:kVersion forKey:@"version"];//	版本号	必选
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.squarePage] forKey:@"page"];//页码：默认第一页 	必选
    [dict setObject:@"20" forKey:@"pagesize"];//每页显示数量：默认每页20条
    [dict setObject:[self.pidAndGid objectForKey:@"gid"] forKey:@"gid"];//	圈子id: 默认为0
    [dict setObject:[self.pidAndGid objectForKey:@"pid"] forKey:@"pid"];//	一级圈子id：默认为0
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.type] forKey:@"type"];//	筛选类型:默认为0  1：置顶2：精华3：new 4：是否图片5：无图帖6：推荐
    [dict setObject:@"dateline" forKey:@"order"];//order	排序dateline： 最新发表lastpost： 最新回复top置顶排序
    
    [dict setObject:self.fkSearchBar.searchTextField.text forKey:@"q"];//q	搜索的字符串



    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,THREAD_LIST] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
            [self.squareView reloadData];

        }else{
            if (self.threadListBaseClass.data==0) {
                self.threadListBaseClass = [ThreadListBaseClass modelObjectWithDictionary:responseObject];
                [self.squareView reloadData];


            }else{
                
                
                
                
                if ([[(ThreadListBaseClass*)[ThreadListBaseClass modelObjectWithDictionary:responseObject] data] isKindOfClass:[NSArray class]]) {
                    
                    
                    if (self.squarePage==1) {
                        [self.threadListBaseClass.data removeAllObjects];
                    }
                    
                        if ([[(ThreadListBaseClass*)[ThreadListBaseClass modelObjectWithDictionary:responseObject] data]count]>0) {
                            [self.threadListBaseClass.data addObjectsFromArray:[(ThreadListBaseClass*)[ThreadListBaseClass modelObjectWithDictionary:responseObject] data]];
                            
                            [self.squareView reloadData];
                            
                        }
                        
                        
                        

                    
                }
                
            }
            
            
            NSArray *jsonDictArr = [self.threadListBaseClass.data isEqual:[NSNull null]]?nil:self.threadListBaseClass.data;

            if (jsonDictArr!=nil) {
                self.squarePage++;

                
            }else{
                if (self.squarePage>1) {
                    //MyNSLog("下拉无数据");
                }
            }
            
        }
        
        
//        if (squareInt==1) {
//            [self hiddenActionView];
        
//        }else{
//            [self.squareView footerEndRefreshing];
//        }
        
        if (squareInt==1) {
            
            [self.squareView setContentOffset:CGPointMake(0, self.fkSearchBar.frame.size.height) animated:YES];
            [self.squareView setContentSize:CGSizeMake(kScreenWidth, self.squareView.frame.size.height+44)];

            squareInt++;

        }
        [UIView animateWithDuration:0.0f animations:^{
            self.squareView.hidden = NO;
            self.circleView.hidden = YES;
            
        }];

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
     [self hiddenActionView];
        [self.squareView footerEndRefreshing];
        [self.squareView headerEndRefreshing];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (squareInt==1) {
            [self hiddenActionView];
            
//        }else{
            [self.squareView footerEndRefreshing];
            [self.squareView headerEndRefreshing];

//        }
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

        [self.squareView reloadData];
        
//        if (self.squareView.hidden&&self.circleView.hidden) {
//            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 100, kScreenWidth-15*2, 0) text:@"点击屏幕刷新数据" font:[UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13] textColor:TITLE_ARTICLE_CONTENTFONT_COLOR backgroundColor:[UIColor clearColor] numberOfLines:0 lineSpacing:5];
//            label.textAlignment = NSTextAlignmentCenter;
//            label.frame = CGRectMake((kScreenWidth-label.frame.size.width)/2, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
//            [self.view addSubview:label];
//            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(reload:)];
//            [self.view addGestureRecognizer:tap];
//            
//
//        }
        

        

    }];

}
-(void)reload:(UITapGestureRecognizer*)tap{
    [self segmentedControlClick:self.segmentedControl];
    [self.view removeGestureRecognizer:tap];
}

/**
 *  未关注圈子的数据加载
 */
-(void)loadCircleDataPop:(UIButton *)sender{
    
    
    
    if (self.popViewArray.count > 0) {
        [self creatPopView:sender];

        return;
    }
    
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:@"0" forKey:@"pid"];
    [dict setObject:@"20" forKey:@"pagesize"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_LIST] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            [self.popViewArray removeAllObjects];
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                CircleModelData *circlemodelData = [CircleModelData modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                [self.popViewArray addObject:circlemodelData];
            }
            
       
            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            // 2.2.获得文件的全路径
            NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",LOCAL_GROUP_LISTONE_key]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            if (![fileManager fileExistsAtPath:path]) {//没文件的情况
                [fileManager createFileAtPath:path contents:nil attributes:nil];

            [responseObject writeToFile:path atomically:YES];
                
                NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:path];
                //MyNSLog("%@",dict);
                
            }

            
            [self creatPopView:sender];
            
            
        }
        
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self showCustomHudSingleLine:@"请检查网络"];

        
    }];
    
}
/**
 *  二级菜单加载
 *
 *  @param index <#index description#>
 */
-(void)loadCircleDataPopTow:(NSInteger)index{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:[NSString stringWithFormat:@"%@",[(CircleModelData *)[self.popViewArray objectAtIndex:index] gid]] forKey:@"pid"];
    [dict setObject:@"20" forKey:@"pagesize"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_LIST] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            [self.secondCircleArray removeAllObjects];
            
            
            GroupUserModel *circlemd = [[GroupUserModel alloc]init];
            
            [self.pidAndGid setObject:@"0" forKey:@"pid"];
            [self.pidAndGid setObject:[NSString stringWithFormat:@"%@",[(CircleModelData *)[self.popViewArray objectAtIndex:index] gid]] forKey:@"gid"];
            [circlemd setGid:[self.pidAndGid objectForKey:@"gid"]];
            [circlemd setPid:[self.pidAndGid objectForKey:@"pid"]];
            [circlemd setTitle:@"全部"];
            [self.secondCircleArray addObject:circlemd];

            
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                GroupUserModel *groupUserModel = [GroupUserModel modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                [self.secondCircleArray addObject:groupUserModel];
            }
            
            NSMutableArray *tempArray = [[NSMutableArray alloc]initWithCapacity:10];
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]initWithCapacity:10];
            NSMutableDictionary *titletempDict = [[NSMutableDictionary alloc]initWithCapacity:10];

            for (int i=0; i<self.secondCircleArray.count; i++) {
                


                [tempArray addObject:[(CircleModelData*)[self.secondCircleArray objectAtIndex:i] title]];

                
            
                
            }
            
            [titletempDict setObject:tempArray forKey:@"title"];
            
            [tempDict addEntriesFromDictionary:self.pop1.titleAndImageRightDict];
            [tempDict setObject:titletempDict forKey:[(CircleModelData*)[self.popViewArray objectAtIndex:index] title]];
            [self.pop1 setTitleAndImageRightDict:tempDict index:index];
            
            
            
            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            // 2.2.获得文件的全路径
            NSString *path = [doc stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",[(CircleModelData*)[self.popViewArray objectAtIndex:index] title]]];
            NSFileManager *fileManager = [NSFileManager defaultManager];

            
            if (![fileManager fileExistsAtPath:path]) {//没文件的情况
                [fileManager createFileAtPath:path contents:nil attributes:nil];
                

                [responseObject writeToFile:path atomically:YES];
            
            }

            
            
            
            
            
            
            
            
        }
        [self hiddenActionView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
    }];
    
}

/**
 *  未关注圈子的数据加载
 */
-(void)loadCircleData{
    
//    [self showActionView];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:@"1" forKey:@"page"];
    [dict setObject:@"0" forKey:@"pid"];
    [dict setObject:@"20" forKey:@"pagesize"];
    
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_LIST] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{
            [self.circleArray removeAllObjects];
            for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                CircleModelData *circlemodelData = [CircleModelData modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                [self.circleArray addObject:circlemodelData];
            }
            [self.circleView reloadData];

        }
        
//        [self hiddenActionView];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [self hiddenActionView];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];


    }];
    
}
/**
 *  已经关注列表的数据加载
 */
-(void)loadMyAttentionCircleData{
//    [self showActionView];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_USER] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
        }else{


                [self.circleArray removeAllObjects];
                for (int i=0; i<[[responseObject objectForKey:@"data"] count]; i++) {
                    GroupUserModel *groupUserModel = [GroupUserModel modelObjectWithDictionary:[[responseObject objectForKey:@"data"] objectAtIndex:i]];
                    //判断是否有关注圈子
                    if (![groupUserModel.pid isEqualToString:@"0"]) {
                        [self.segmentedControl setTitle:@"我的圈子" forSegmentAtIndex:1];
                        if ([[self.segmentedControl titleForSegmentAtIndex:1] isEqualToString:@"我的圈子"]) {
                            UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
                            [rightButton setImage:[UIImage imageNamed:@"公用_更多"] forState:UIControlStateNormal];
                            [rightButton addTarget:self action:@selector(rightButtonAddMoreClicked:) forControlEvents:UIControlEventTouchUpInside];
                            UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
                            self.navigationItem.rightBarButtonItem = rightBarButtonItem;
                            [self redDot];
                        }
                    }

                    [self.circleArray addObject:groupUserModel];
                }
                [self.circleView reloadData];

            //MyNSLog("responseObject=====%@",responseObject);
           
            
        }
        
//        [self hiddenActionView];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [self hiddenActionView];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];


    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resourSegmentedControlces that can be recreated.

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark UIScrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    
    int index = fabs(scrollView.contentOffset.x) / scrollView.frame.size.width;
        self.segmentedControl.selectedSegmentIndex = index;
    
    if (index==0) {
        [self squareleftAndRightButton];

    }else if(index==1){
        [self squareRightButton];

    }
    
    
    
//    [self.switcher forceSelectedIndex:index animated:YES];
    //index为当前页码
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger number=0;
    if (self.squareView==tableView) {
        number = 1;
    }else if (self.circleView==tableView){
        number = 1;

    }
    return number;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger number=0;

   if (self.squareView==tableView) {
        number = self.threadListBaseClass.data.count;
    }else if (self.circleView==tableView){
        number = self.circleArray.count;
    }
    return number;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger hight=44;
    if (self.squareView==tableView) {
        hight = [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
    }else if (self.circleView==tableView){
        hight = CIRCLETABLEVIEWCELL_HIGHT;
        
    }
    return hight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    
    

    static NSString *ID = nil;
    UITableViewCell *cell = nil;
    if (self.squareView==tableView) {
        ID=@"tableViewCell";
        cell = [tableView dequeueReusableCellWithIdentifier:ID];

        if (cell == nil) {
//            cell = [[[NSBundle mainBundle] loadNibNamed:@"SquareTableViewCell" owner:self options:nil] lastObject];
            cell = [[SquareATableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }

        
        [[(SquareATableViewCell*)cell title] setText:[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] subject]]];
        [[(SquareATableViewCell*)cell content] setText:[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data  objectAtIndex:indexPath.row] summary]]];


        
        NSMutableArray *arrimages = [[NSMutableArray alloc ]initWithArray:[(ThreadListData*)[self.threadListBaseClass.data  objectAtIndex:indexPath.row] pic]];
        

            [(SquareATableViewCell*)cell setSquareCellImageViewsArray:arrimages];

        [[(SquareATableViewCell*)cell timesLabel] setText:[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data  objectAtIndex:indexPath.row] dateline]]];
        
        [(SquareATableViewCell*)cell bottomView].tag =indexPath.row;
        
        
        NSArray *numberArry =[[NSArray alloc]initWithObjects:
                              [NSString stringWithFormat:@"%d",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] collection]],
                              [NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] good]],
                              [NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] replies]],nil];
                               
        [(SquareATableViewCell*)cell setArrayNumber:numberArry];
        
        
        NSMutableArray *array =[[NSMutableArray alloc]initWithCapacity:10];
        /**
         *          digest	是否加精1：是0：否
         *
         */
        if ([[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] digest]] isEqualToString:@"1"]) {
            [array addObject:[NSNumber numberWithInteger:SquareMarkStyleRefinement]];
        }
        /**
         *              top	是否置顶1：是0：否

         *
         */
        if ([[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] top]] isEqualToString:@"1"]) {
            [array addObject:[NSNumber numberWithInteger:SquareMarkStylePeak]];
        }
        /**
         * new	是否new 1：是0：否
         *
         */
        if ([[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] aNew]] isEqualToString:@"1"]) {
            [array addObject:[NSNumber numberWithInteger:SquareMarkStyleNew]];
        }
        /**
         * ispic	是否图片 1：是0：否
         *
         */
        if ([[NSString stringWithFormat:@"%@",[(ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row] ispic]] isEqualToString:@"0"]) {
//            [array addObject:[NSNumber numberWithInteger:SquareMarkStyleNot]];
        }else{
            [array addObject:[NSNumber numberWithInteger:SquareMarkStyleAdsum]];

        }
        
        
        
//        SquareMarkStyleAll = 0,//全
//        SquareMarkStyleRefinement,//精
//        SquareMarkStylePeak,//顶
//        SquareMarkStyleNew,//新
//        SquareMarkStyleAdsum,//有
//        SquareMarkStyleNot//无
//        
//        isrec	是否推荐1：是0：否
//        new	是否new 1：是0：否
//        ispic	是否图片 1：是0：否
//        closed	是否关闭回复1：是0：否

        
        
        [(SquareATableViewCell*)cell setSquareMarkStyles:array];

        [(SquareATableViewCell*)cell squareCellImageView].tag = indexPath.row;
        
        [(SquareATableViewCell*)cell setDelegate:self];

        
        
        

    }else if (self.circleView==tableView){

        if (kScreenWidth == 414) {
            ID = @"tableViewCell414";
        }else{
            ID=@"tableViewCell";
        }
        cell = [tableView dequeueReusableCellWithIdentifier:ID];

        if (cell == nil) {
            if (kScreenWidth == 414) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"CircleTableViewCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"CircleTableViewCell" owner:self options:nil] firstObject];

            }
            /**
             *  线条的处理
             */
            
            UIView *bottomLineView = [[UIView alloc]init];
            
            if (indexPath.row != self.circleArray.count - 1)
            {
                bottomLineView.frame = CGRectMake(70, CIRCLETABLEVIEWCELL_HIGHT-0.5,kScreenWidth-70 - 5, 0.5);
            }
            else
            {
                bottomLineView.frame = CGRectMake(0, CIRCLETABLEVIEWCELL_HIGHT-0.5, kScreenWidth, 0.5);
            }
            
            bottomLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
            [cell.contentView addSubview:bottomLineView];
            
        }
        [[(CircleTableViewCell *)cell icon] setImageURLStr:[NSString stringWithFormat:@"%@",[[self.circleArray objectAtIndex:indexPath.row] icon]] placeholder:[UIImage imageNamed:@"公用_默认图片"]];
        
        [(CircleTableViewCell *)cell title].text = [[self.circleArray objectAtIndex:indexPath.row] title];
        [(CircleTableViewCell *)cell subtitle].text =[[self.circleArray objectAtIndex:indexPath.row] lastposttitle];
//        GroupUserModel
        
        [[(CircleTableViewCell *)cell thread] setTitle:[NSString stringWithFormat:@" %@",[[self.circleArray objectAtIndex:indexPath.row] threads]] forState:UIControlStateNormal];
        [[(CircleTableViewCell *)cell post] setTitle:[NSString stringWithFormat:@" %@",[[self.circleArray objectAtIndex:indexPath.row] posts]] forState:UIControlStateNormal];

        [(CircleTableViewCell *)cell pushImage].hidden = YES;
        

        
        
    }
    // Configure the cell...

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.circleView) {
        if ([[(GroupUserModel*)[self.circleArray objectAtIndex:indexPath.row] pid] isEqualToString:@"0"]) {
            CircleSecondLevelViewController *cslVC = [[CircleSecondLevelViewController alloc] initWithNibName:@"CircleSecondLevelViewController" bundle:nil];
            cslVC.circleModelData = [self.circleArray objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:cslVC animated:YES];
        }else{
            CirclePostsDetailsViewController *cplVC = [[CirclePostsDetailsViewController alloc]initWithNibName:@"CirclePostsDetailsViewController" bundle:nil];
            cplVC.groupUserModel =[self.circleArray objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:cplVC animated:YES];
        }
    


    }else  if (self.squareView==tableView){

        if (nil!=self.threadListBaseClass.data&&self.threadListBaseClass.data.count>0) {
            SquarePostsDetailsViewController *spdVC = [[SquarePostsDetailsViewController alloc] initWithNibName:@"SquarePostsDetailsViewController" bundle:nil];

            spdVC.threadListData = (ThreadListData*)[self.threadListBaseClass.data objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:spdVC animated:YES];
        }

    }
    

}
- (void)tableView:(UITableView *)tableView

commitEditingStyle:(UITableViewCellEditingStyle) editingStyle

forRowAtIndexPath:(NSIndexPath *) indexPath

{
    
    if (tableView==self.circleView) {
        if (editingStyle == UITableViewCellEditingStyleDelete)
            
        {
            
            [self guanzhu:@"out" gid:[[self.circleArray objectAtIndex:indexPath.row] gid] indexPath:indexPath];
            
        }
    }

    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView

           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath      //当在Cell上滑动时会调用此函数

{
    @try{
        if (self.circleView == tableView) {
            
            
            
            if (![[(GroupUserModel*)[self.circleArray objectAtIndex:indexPath.row] pid] isEqualToString:@"0"])
                return  UITableViewCellEditingStyleDelete;  //返回此值时,Cell会做出响应显示Delete按键,点击Delete后会调用下面的函数,别给传递UITableViewCellEditingStyleDelete参数
            
            else
                
                return  UITableViewCellEditingStyleNone;   //返回此值时,Cell上不会出现Delete按键,即Cell不做任何响应
            
        }else{
        return  UITableViewCellEditingStyleNone;
        }
    }
    @catch(NSException *exception) {
        //MyNSLog("exception:%@", exception);
    }
    
    @finally {
        
    }
}







- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
return @"取消关注";
}

//添加取消关注
-(void)guanzhu:(NSString *)actionStr gid:(NSString *)gid indexPath:(NSIndexPath*)indexPath{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:actionStr forKey:@"action"];
    [dict setObject:gid forKey:@"gid"];
    
    
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,GROUP_CHANGEUSERGROUP] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
                
            }else{
                if ([actionStr isEqualToString:JOIN]) {
                    [self showCustomHudSingleLine:@"关注失败"];
                    
                }else if ([actionStr isEqualToString:OUT]) {
                    [self showCustomHudSingleLine:@"取消失败"];
                    
                }
            }
        }else{
          
            
            [self.circleArray removeObjectAtIndex:indexPath.row];
            [self.circleView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            
            if ([[responseObject objectForKey:@"msg"] length]>0) {
                [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];
                
            }else{
                if ([actionStr isEqualToString:JOIN]) {
                    [self showCustomHudSingleLine:@"关注成功"];
                    
                }else if ([actionStr isEqualToString:OUT]) {
                    [self showCustomHudSingleLine:@"取消成功"];
                    
                }
                
            }
        }
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self showCustomHudSingleLine:@"请检查网络"];
        
    }];
}
#pragma mark -
#pragma mark -- SquareCellImageViewsDelegate
-(void)squareCellImageViewsIndex:(NSInteger)index subImageIndex:(NSInteger)imageIndex{
//    MyNSLog("第%d个cell的第 %d 个image", index,imageIndex);
}
-(void)bottomViewIndex:(NSInteger)index subImageIndex:(NSInteger)buttonIndex{
//    MyNSLog("第%d个cell的第 %d 个button", index,buttonIndex);


}
/**
 *  是否登录，登录成功后
 */
-(void)Login{
    switch (self.logintag) {
        case 0:
        {
            
            AddCircleViewController *addCircleVC = [[AddCircleViewController alloc]initWithNibName:@"AddCircleViewController" bundle:nil];
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
            for (int i=0; i<self.circleArray.count; i++) {
                //MyNSLog("%@",[(CircleModelData*)[self.circleArray objectAtIndex:i] pid] );
                if (![[(CircleModelData*)[self.circleArray objectAtIndex:i] pid] isEqualToString:@"0"]) {
                    [dict setObject:[[self.circleArray objectAtIndex:i] gid] forKey:[[self.circleArray objectAtIndex:i] title]];
                    
                }
            }
            addCircleVC.attentionDict = [[NSMutableDictionary alloc]initWithDictionary:dict];
            [self.navigationController pushViewController:addCircleVC animated:YES];
        }
            break;
        case 1:
        {
            
            AssociatedWithIViewController *associatedWithIViewController = [[AssociatedWithIViewController alloc]initWithNibName:@"AssociatedWithIViewController" bundle:nil];
            associatedWithIViewController.title = @"与我相关";
            [self.navigationController pushViewController:associatedWithIViewController animated:YES];
        }
            break;
            
        default:
            break;
    }
   
}

#pragma mark -
#pragma mark -- FKSearchBarDelegate


- (void)VoiceConversion{
    [self.fkSearchBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    self.fkSearchBar.searchTextField.text = voice;
    self.squarePage = 1;
    //[self.threadListBaseClass.data removeAllObjects];
    [self loadSquareData];
}

- (void)SearchString{
    [self.fkSearchBar.searchTextField resignFirstResponder];
    if (self.fkSearchBar.searchTextField.text>0) {
        [self.pidAndGid setObject:@"0" forKey:@"pid"];
        [self.pidAndGid setObject:@"0" forKey:@"gid"];
        self.type = 0;
        self.squarePage = 1;
        //[self.threadListBaseClass.data removeAllObjects];
        [self loadSquareData];
    }

    
    
}




@end
